var util = require("../../../utils/util.js")
var app = getApp()
Page({
  data: {
    movies: {},
    navigateTitle: "",
    requestUrl: "",
    totalCount: 0,
    isEmpty: true
  },

  onLoad: function (options) {
    var dataUrl = ""
    switch (options.cagetory) {
      case "正在热映":
        dataUrl = app.globalData.doubanBase + "/v2/movie/in_theaters"
        break
      case "即将上映":
        dataUrl = app.globalData.doubanBase + "/v2/movie/coming_soon"
        break
      case "豆瓣Top250":
        dataUrl = app.globalData.doubanBase + "/v2/movie/top250"
        break
    }
    util.http(dataUrl, this.processDoubanData)
    var cagetory = options.cagetory
    this.setData({
      navigateTitle: cagetory,
      requestUrl: dataUrl
    })
  },
  processDoubanData: function (moviesDouban) {
    var movies = [];
    for (var idx in moviesDouban.subjects) {
      var subject = moviesDouban.subjects[idx]
      var title = subject.title
      if (title.length >= 6) {
        title = title.substring(0, 6) + "..."
      }
      //[1,1,1,1,1] [1,1,1,0,0]

      var temp = {
        stars: util.convertToStarsArray(subject.rating.stars),
        title: title,
        average: subject.rating.average,
        coverageUrl: subject.images.large,
        movieId: subject.id
      }
      movies.push(temp)
    }
    var totalCount = this.data.totalCount
    var totalMovies = {}

    if (!this.data.isEmpty) {
      totalMovies = this.data.movies.concat(movies)
    }
    else {
      totalMovies = movies
      this.data.isEmpty = false
    }
    this.setData({
      movies: totalMovies,
      totalCount: totalCount += 20
    });
    wx.hideNavigationBarLoading()
    wx.stopPullDownRefresh()
  },
  onReady() {
    wx.setNavigationBarTitle({
      title: this.data.navigateTitle
    })
  },
  onReachBottom() {
    var nextUrl = this.data.requestUrl + "?start=" + this.data.totalCount + "&count=20"
    util.http(nextUrl, this.processDoubanData)
    wx.showNavigationBarLoading()
  },
  onPullDownRefresh() {
    var refreshUrl = this.data.requestUrl + "?start=0&count=20"
    this.data.movies = {}
    this.data.isEmpty = true
    this.data.totalCount = 0
    util.http(refreshUrl, this.processDoubanData)
    wx.showNavigationBarLoading()
  },
  onMovieTap(event) {
    var movieId = event.currentTarget.dataset.movieid;
    wx.navigateTo({
      url: '../movie-detail/movie-detail?id=' + movieId,
      fail(error) {
        console.log(error)
      }
    })

  }
})